package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.service.impl.AccountServiceImpl;
import com.lagou.utils.TransManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: spring_transfer
 * @description:
 * @author: Mr.Wang
 * @create: 2020-12-16 14:36
 **/
@Component
public class JdkProxyFactory {

	@Autowired
	private AccountService accountService;


	@Autowired
	private TransManage transactionManager;

	/*
		采用JDK动态代理技术来生成目标类的代理对象
		 ClassLoader loader, : 类加载器：借助被代理对象获取到类加载器
		 Class<?>[] interfaces, ： 被代理类所需要实现的全部接口
		 InvocationHandler h ： 当代理对象调用接口中的任意方法时，那么都会执行InvocationHandler中invoke方法
	 */
	public AccountService createAccountSericeJDKProxy(){

		AccountService accountServiceProxy= (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {

			@Override
			//   proxy: 当前的代理对象引用   method：被调用的目标方法的引用   args：被调用的目标方法所用到的参数
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

				if(method.getName().equals("transfer")) {
					try {
						transactionManager.beginTransaction();
						method.invoke(accountService, args);
						transactionManager.commit();
					} catch (Exception e) {
						e.printStackTrace();
						// 手动回滚事务
						transactionManager.rollback();
					} finally {
						// 手动释放资源
						transactionManager.close();
					}
				}

				return null;
			}
		});


		return  accountServiceProxy;
	}
}
